package com.xpgk.mvc.statistic.dlStatistic;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.xpgk.mvc.base.BaseController;
import com.xpgk.mvc.deptStation.DeptStation;
import com.xpgk.mvc.organization.Organization;
import com.xpgk.mvc.statistic.monthTotalStatistic.MonthTotal;
import com.xpgk.mvc.user.User;

public class DlMonthTotalStatisticController  extends  BaseController{
	
	public void	index()
	{	
		User user = getCUser();
		DeptStation deptStation = DeptStation.dao.findById(user.getStr(User.column_stationids));
		if(deptStation!=null && deptStation.getStr(DeptStation.column_parentids)!=null){
			setAttr("mangerIds",getCUserIds() );
		}else{
			setAttr("mangerIds","111");
		}
		String organids = getCUserOrganIds();
		Organization organ =  Organization.dao.findById(organids);
		setAttr("organ",organ );
		setAttr("organids", organids);
		render("dlMonthTotalStatistic.html");
	}
	
	
	public void getMonthTotal() throws ParseException
	{
		String monthStr = (String) splitPage.getQueryParam().get("date");//2018-04
		String mangerIds = (String) splitPage.getQueryParam().get("mangerIds");
		String year = monthStr.substring(0, 4);//2018
		
		String orgSql = "SELECT a.organids as organids ,b.name as orgname FROM sb_customer_total_daily a LEFT JOIN sys_organization b ON a.organids = b.ids WHERE b.parentIds = ? AND DATE_FORMAT(date,  '%Y-%m') = ?  GROUP BY a.organids";
		List<Record> orgList =null;
		if(mangerIds!=null && !mangerIds.equals("")){
			orgSql = "SELECT a.organids as organids ,b.name as orgname FROM sb_customer_total_daily a LEFT JOIN sys_organization b ON a.organids = b.ids WHERE b.parentIds = ? AND DATE_FORMAT(date,  '%Y-%m') = ? and b.mangerIds = ? GROUP BY a.organids";
			orgList =Db.find(orgSql,getCUserOrganIds(),monthStr,mangerIds);
			
		}else{
			orgList =Db.find(orgSql,getCUserOrganIds(),monthStr);
		}
		
		String sql  = getSqlMy(MonthTotal.sqlId_getOnemonthTotalList);
		String dntsql  = getSqlMy(MonthTotal.sqlId_getmonthTotalList);
		String dnurse = "SELECT COUNT(ids) as fwrs,SUM(gjWeight) as sjjzjs FROM sb_customer_service_nurse WHERE YearMon = ? and organids = ?";
		String yjjsSql = "SELECT SUM(delWeight) as yjjs from sb_customer_detail WHERE  DATE_FORMAT(firstDate, '%Y-%m') = ? AND organIds = ? and dataStatus in ('1','2')";
		String xgkSql = "SELECT customerIds FROM sb_customer_detail WHERE  DATE_FORMAT(firstDate, '%Y') = ? AND organIds = ? and dataStatus in ('1','2')";
		
		
		String sgksjjsSql = "SELECT sum( gjWeight ) as gjWeight from sb_customer_service_nurse WHERE organids = ? and YearMon = ? and isXgk = '1'";
		String sjjsSql = "SELECT SUM(gjWeight) as sjjs from sb_customer_service_nurse WHERE organids = ? and YearMon = ?";
		
		List<Record> records = new ArrayList<>();
		
		if(orgList!=null && orgList.size()>0){
			for(int i = 0;i<orgList.size();i++){
				double yjjsSum = 0d;
				double sjjsSum = 0d;
				String organIds = orgList.get(i).getStr("organids");
				List<Record>  dntList =  Db.find(dntsql, organIds,year);
				Record  r =  Db.findFirst(sql,organIds ,monthStr);
				//添加服务人数、实际减重斤数
				Record record = Db.findFirst(dnurse,monthStr,organIds);
				if(record!=null){
					String fwrs = record.getLong("fwrs")+"";
					if(fwrs!=null && !fwrs.equals("")){
						r.set("fwrs", fwrs);
					}
					if(record.getDouble("sjjzjs")!=null ){
						r.set("sjjzjs", new DecimalFormat("#.0").format( record.getDouble("sjjzjs")) );
					}
				}
				
				//添加当年当月新增顾客应减斤数
				Record yjjsRecord = Db.findFirst(yjjsSql,monthStr,organIds);
				double yjjs = 0d;
				if(yjjsRecord.getDouble("yjjs")!=null ){
					r.set("xgkyjjs", yjjsRecord.getDouble("yjjs"));
					yjjs =yjjsRecord.getDouble("yjjs");
				}
				//添加当年当月新增顾客实减斤数
				//添加当年当月新增顾客实减斤数
				Record xgkRecord = Db.findFirst(sgksjjsSql,organIds,monthStr);
				double sjjs = 0d;
				if(xgkRecord.getDouble("gjWeight")!=null ){
					r.set("dndyxgksjjs", xgkRecord.getDouble("gjWeight"));
				}
//				List<Record> xgkRecord = Db.find(xgkSql,year,organIds);
//				double sjjs = 0d;
//				if(xgkRecord!=null && xgkRecord.size()>0){
//					for (Record xgk:xgkRecord) {
//						String customerIds = xgk.getStr("customerIds");
//						Record gjRecord = Db.findFirst(sgksjjsSql,customerIds,monthStr);
//						if(gjRecord!=null ){
//							if(gjRecord.getFloat("gjWeight")!=null ){
//								sjjs = sjjs+gjRecord.getFloat("gjWeight");
//								
//							}
//							
//						}
//					}
//					//sjjsSum = sjjsSum + sjjs;
//					r.set("dndyxgksjjs", new DecimalFormat("0.0").format( sjjs) );
//				}
				//添加实减斤数
				Record sjjsRecord = Db.findFirst(sjjsSql,organIds,monthStr);
				if(sjjsRecord!=null && sjjsRecord.getDouble("sjjs")!=null){
					r.set("sjjzjs", sjjsRecord.getDouble("sjjs"));
				}
				//添加累计减重率
				
				for(Record dnt:dntList){
					
					int month = dnt.getInt("date");
					String monthStr2 = month+"";
					if(month<10){
						monthStr2 = "0"+monthStr2;
					}
					String yearMonth = year+"-"+monthStr2;//2017-04
					
					//当年当月新增顾客应减斤数
					Record yjjsRecord1 = Db.findFirst(yjjsSql,yearMonth,organIds);
					double yjjs1 = 0d;
					if(yjjsRecord1.getDouble("yjjs")!=null ){
						yjjs1 =yjjsRecord1.getDouble("yjjs");
						yjjsSum = yjjsSum +yjjs1;
					}
					if(yjjsSum!=0){
					//当年当月新增顾客实减斤数
						double sjjs1 = 0d;
						Record xgkRecord1 = Db.findFirst(sgksjjsSql,organIds,yearMonth);
						
						if(xgkRecord1.getDouble("gjWeight")!=null ){
							sjjsSum = xgkRecord1.getDouble("gjWeight");
						}
						
				/*	List<Record> xgkRecord1 = Db.find(xgkSql,year,organIds);
					double sjjs1 = 0d;
					if(xgkRecord1!=null && xgkRecord1.size()>0){
						for (Record xgk:xgkRecord1) {
							String customerIds = xgk.getStr("customerIds");
							Record gjRecord = Db.findFirst(sgksjjsSql,customerIds,yearMonth);
							if(gjRecord!=null ){
								if(gjRecord.getFloat("gjWeight")!=null ){
									sjjs1 = sjjs1+gjRecord.getFloat("gjWeight");
								}
								
							}
						}
						sjjsSum = sjjsSum + sjjs1;
					}*/
					if(monthStr.equals(yearMonth)){
						r.set("ljjzl", (sjjsSum/yjjsSum)*100);
						break;
					}
				}
			}
			
				r.set("orgname", orgList.get(i).getStr("orgname"));
				r.set("organids", orgList.get(i).getStr("organids"));
				records.add(r);
			}
		}
		renderJson(records);
		
		/*SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy");
		Date month = sdf.parse(monthStr);
		String yearStr2 = sdf2.format(month);//本年
		Date year = sdf2.parse(yearStr2);
		
		
		
		
		Calendar cal=Calendar.getInstance();
		cal.setTime(month);
		cal.add(Calendar.MONTH,-1);
		String lastMonthStr = sdf.format(cal.getTime());
		splitPage.getQueryParam().put("lastMonth",lastMonthStr);//上月
		Calendar cal2=Calendar.getInstance();
		cal2.setTime(month);
		cal2.add(Calendar.YEAR,-1);
		String lastYearStr = sdf.format(cal2.getTime());
		
		Calendar cal3=Calendar.getInstance();
		cal3.setTime(year);
		cal3.add(Calendar.YEAR,-1);
		String lastYearStr2 = sdf2.format(cal3.getTime());
		splitPage.getQueryParam().put("lastYear",lastYearStr);//上年同期
		splitPage.getQueryParam().put("year",yearStr2);//本年
		splitPage.getQueryParam().put("lastYear2",lastYearStr2);//本年
		String json = paging(splitPage,MonthTotal.sqlId_splitPageSelect,MonthTotal.sqlId_splitPageFrom);
		String str = json.substring(0,json.length() - 3);
		String str2 = ","+"\""+"n"+"\""+":"+n+"}]}";
		json = str+str2;
		//setAttr("n", n);
		renderJson(json);*/
	}
	

	public void getN() throws ParseException {
		
		String date = getPara("date");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy");
		Date month = sdf.parse(date);
		String yearStr2 = sdf2.format(month);//本年
		Date year = sdf2.parse(yearStr2);
		
		Calendar cal3=Calendar.getInstance();
		cal3.setTime(year);
		cal3.add(Calendar.YEAR,-1);
		String lastYearStr2 = sdf2.format(cal3.getTime());
		String n = "1";//本年有几个月有数据
		String lastN = "1";//上年有几个月有数据
		//String now = sdf2.format(new Date());
		//int result = yearStr2.compareTo(now);
		/*if(result<0){//如果查询时间小于当前的时间
			n = "12";
		}else{*/
			String sql = getSqlMy(MonthTotal.sqlId_month);
			MonthTotal monthTotal = MonthTotal.dao.findFirst(sql,getCUserOrganIds(),yearStr2);
			if(monthTotal!=null){
				String m = monthTotal.getStr(MonthTotal.column_date);
				n = m.substring(5, 7);
				if(n.substring(0, 1).equals("0")){
					n = n.substring(1, 2);
				}
			}
			
			MonthTotal lastMonthTotal = MonthTotal.dao.findFirst(sql,getCUserOrganIds(),lastYearStr2);
			if(lastMonthTotal!=null){
				String m = lastMonthTotal.getStr(MonthTotal.column_date);
				lastN = m.substring(5, 7);
				if(lastN.substring(0, 1).equals("0")){
					lastN = lastN.substring(1, 2);
				}
			}
			
	//	}
		Map<String, Object> mm = new HashMap<>();
		mm.put("msg", "200");
		// 获取当前登录机构id
		mm.put("n", n);
		mm.put("lastN", lastN);
		renderJson(mm);
	}
}
